import type { UnwrapRef } from 'vue'

export default function useVModel<
  P extends object,
  N extends keyof P,
  E extends (event: string, value: P[N]) => void
>(props: P, name: N, emit: E) {
  const model = ref(props[name])

  watch(
    () => props[name],
    () => {
      model.value = props[name] as UnwrapRef<P[N]>
    }
  )

  watch(
    model,
    () => {
      emit(`update:${name as string}`, model.value as P[N])
    },
    { deep: true }
  )

  return model
}
